/****************
 *@description:  上传礼物 编辑礼物 礼物详情  myPocket/giftManage/detail
 *@author: Xhd
 *@API: 陈浩天
 *@date: 2023-11-27 16:54:33
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { Form, Input, InputNumber, Button, Space } from "antd";
import TheUpload from "@/components/TheUpload";
import TheImage from "@/components/TheImage";
import { apiGiftInfoAdd, apiGiftInfoInfo, apiGiftInfoModify } from "@/request/giftManage";

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
};

class UploadGift extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      type: "",
      giftId: "",
      disabled: false,
      btnLoading: false,
      initialValues: {},
      accept: ['image/png'],
      giftImgFileList: [],
      giftTagImgFileList: [],
    }
  }

  async componentDidMount() {
    const { type, id } = this.props.match.params
    let disabled
    if (type === "info") {
      disabled = true
      let res = await apiGiftInfoInfo({ giftId: id })
      if (res.code === 0 && res.data) {
        let giftImgFileList = [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: res.data.giftImg,
          },
        ]
        let giftTagImgFileList = []
        if (res.data.giftTagImg) {
          giftTagImgFileList = [
            {
              uid: '-1',
              name: 'image.png',
              status: 'done',
              url: res.data.giftTagImg,
            },
          ]
        }
        res.data.giftPrice = res.data.giftPrice /10
        this.setState({
          initialValues: res.data,
          giftImgFileList,
          giftTagImgFileList
        })
        this.formRef.setFieldsValue({ ...res.data })
      }
    }
    this.setState({ type, giftId: id, disabled })
    console.log(type, id);
  }

  getFileResult = (data, name) => {
    console.log(data, 'data');
    if (data.length > 0 && data[0].hasOwnProperty('response') && data[0].response) {
      let str = data[0].response.data
      this.formRef.setFieldsValue({ [name]: str })
    } else {
      this.formRef.setFieldsValue({ [name]: '' })
    }
  }

  onFinish = async (values) => {
    const { type, giftId } = this.state
    this.setState({ btnLoading: true })
    values.giftPrice = values.giftPrice * 10
    if (!values.giftBuySize) {
      values.giftBuySize = 1
    }
    if (type === "add") {
      let res = await apiGiftInfoAdd(values)
      if (res.code === 0) {
        React.$message({
          type: "success",
          content: "上传成功"
        })
        this.props.history.go(-1)
      }
    } else {
      let res = await apiGiftInfoModify({ giftId, ...values })
      if (res.code === 0) {
        React.$message({
          type: "success",
          content: "上传成功"
        })
        this.props.history.go(-1)
      }
    }
    this.setState({ btnLoading: false })
  }
  giftNameChange = (e) => {
    e.target.value = e.target.value.replace(/\s/g, '')
    this.formRef.setFieldsValue({giftName: e.target.value})
  }

  render() {
    const { type, accept, disabled, btnLoading, initialValues } = this.state
    return (<div className="p-layout-box">
      <div>
         {type === "add" ? "上传礼物" : type === "info" ? "礼物详情" : "编辑礼物" }
      </div>
      <Form ref={(ref) => this.formRef = ref} onFinish={(values) => this.onFinish(values)}
        {...formItemLayout} labelAlign='right' initialValues={initialValues}
      >
        <Form.Item label="礼物名称" name={"giftName"} rules={[{ required: true }]} >
          <Input disabled={disabled} placeholder="请输入礼物名称" maxLength={10}
            onChange={(e) => this.giftNameChange(e) }
          />
        </Form.Item>
        <Form.Item label="礼物图片" name={"giftImg"} rules={[{ required: true },]}
          extra={`格式png ，大小控制在5M；建议比例1:1`}
        >
          {
            disabled ? <TheImage src={initialValues.giftImg} width={100} />
              :
              <TheUpload accept={accept} maxSize={5} fileList={this.state.giftImgFileList} data={{ attachKey: '1' }} len={1}
                getFileResult={(e) => this.getFileResult(e, "giftImg")}

              />
          }
        </Form.Item>
        <Form.Item label="礼物标签" name={"giftTagImg"}
          extra={`格式png ，大小控制在5M`}
        >
          {
            (disabled && initialValues.giftTagImg) ? <TheImage src={initialValues.giftTagImg} width={100} />
              :
              <TheUpload  accept={accept} maxSize={5} fileList={this.state.giftTagImgFileList} data={{ attachKey: '1' }} len={1}
                getFileResult={(e) => this.getFileResult(e, "giftTagImg")}

              />
          }
        </Form.Item>
        <Form.Item label="价格" name={"giftPrice"} rules={[{ required: true }]} >
          <Input type="number" disabled={disabled} placeholder="请设置礼物单价（宠币）" addonAfter="宠币" />
        </Form.Item>
        <Form.Item label="自定义最大购买数量" name={"giftBuySize"} >
          <InputNumber max={99999999} precision={0} disabled={disabled} placeholder="请设置单次最大购买数量（不填则为1）" />
        </Form.Item>
        <Form.Item label="排序" name={"giftSort"} rules={[{ required: true }]} >
          <InputNumber precision={0} disabled={disabled} placeholder="数字越小，在APP展示越靠前" />
        </Form.Item>
        <Form.Item label=' ' colon={false} labelCol={{ xs: { span: 12 }, sm: { span: 5 }, }}>
          {
            (type === "add" || type === "modify") && <Space>
              <Button onClick={() =>{ 
                if(type === "modify"){
                  this.setState({ disabled: true, type: "info" })
                  this.formRef.setFieldsValue({ ...initialValues })
                }else {this.props.history.go(-1)}}}>取消</Button>
              <Button htmlType="submit" type="primary" loading={btnLoading} >提交</Button>
            </Space>
          }
          {
            type === "info" && <Space>
              <Button onClick={() => this.props.history.go(-1)} >返回</Button>
              <Button onClick={() => this.setState({ disabled: false, type: "modify" })} type="primary" >编辑</Button>
            </Space>
          }
        </Form.Item>
      </Form>
    </div>)
  }
}

export default UploadGift
